<?php

/**
 * This is the model class for table "{{menu}}".
 *
 * The followings are the available columns in table '{{menu}}':
 * @property integer $id
 * @property string $item_name
 * @property string $title
 * @property string $description
 * @property integer $submenu
 * @property string $link_title
 * @property string $position
 * @property string $module
 * @property integer $hidden
 * @property integer $type
 *
 *
 *
 */
class Menu extends MenuActiveRecord
{
    //public $content;
    public $body_format;
    public $item_count;
    public $published;
    public $unpublished;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{menu}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('item_name, title, description, link_title, module, hidden, position,pages_count', 'required'),
			array('type,hidden, pages_count', 'numerical', 'integerOnly'=>true),
			array('item_name, title, description, link_title, module', 'length', 'max'=>255),
            array('body_format,item_count','safe'),
            array('published,unpublished,item_count','unsafe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, item_name, title, description, link_title, type, module, hidden', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'menuItem' => array(self::HAS_MANY, 'MenuItem', 'parent_mid'),
			'articles' => array(self::HAS_MANY, 'Article', 'mid'),
		);
	}

	/**
	 * @return array customized attribNULL ute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id'            => 'ID',
			'item_name'     => Yii::t('MenuModule.base','Item Name'),
			'title'         => Yii::t('MenuModule.base','Title'),
			'description'   => Yii::t('MenuModule.base','Description'),
			'link_title'    => Yii::t('MenuModule.base','Link Title'),
			'position'      => Yii::t('MenuModule.base','Position'),
            'type'          => Yii::t('MenuModule.base','Type'),
			'module'        => Yii::t('MenuModule.base','Module'),
			'hidden'        => Yii::t('MenuModule.base','Hidden'),
            'body_format'   =>Yii::t('MenuModule.base','Body Format'),
            'item_count'    =>Yii::t('MenuModule.base','Item count'),
            'unpublished'   =>Yii::t('MenuModule.base','Unpublished'),
            'published'   =>Yii::t('MenuModule.base','Published'),

		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

	//	$criteria->compare('id',$this->id);
		$criteria->compare('item_name',$this->item_name,true);
	//	$criteria->compare('title',$this->title,true);
	//	$criteria->compare('description',$this->description,true);
	//	$criteria->compare('link_title',$this->link_title,true);
	//	$criteria->compare('position',$this->position,true);
	//	$criteria->compare('type',$this->type,true);
	//	$criteria->compare('module',$this->module,true);
	//	$criteria->compare('hidden',$this->hidden);
	//	$criteria->compare('item_count',$this->item_count);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
            'pagination'=>array('pageSize'=>10)
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Menu the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    //Отдаем все модули для select-А
    public function getModulesOptions()
    {
        $items = array();
        $modules = Yii::app()->getModules();
        foreach($modules as $module=>$modulePath)
        {
            if($module !== 'gii')
            {
                $items[] = $module;
            }
        }
        return $items;
    }

    //Отдаем тип меню
    public function getTypeOptions()
    {
        return array('1'=>Yii::t('MenuModule.base','Single Page'),'2'=>Yii::t('MenuModule.base','Multi Page'));
    }

    //Отдаем массив для дропдауна
    public function getHiddenOptions()
    {
        return array('0'=>Yii::t('MenuModule.base','No'),'1'=>Yii::t('MenuModule.base','Yes'));
    }
    public function getHiddenStatus()
    {
        return $this->hidden == true ? Yii::t('MenuModule.base','Yes') : Yii::t('MenuModule.base','No');
    }

    //Возвращаяем тип страницы
    public function getBodyFormatOptions()
    {
        $data = array('full_html'=>'full_html','plain_text'=>'plain_text');

        return $data;
    }

    //Отдаем кол-во статей на одну страницу
    public function getPagesCountOptions()
    {
        return  array('5'=>'5','10'=>'10','20'=>'20','30'=>'30','40'=>'40','50'=>'50');
    }

    //Форматируем дату и время создания
    public function getCreateDateTimeFormat()
    {
        return CHtml::tag('span',array('class'=>'label label-default','style'=>'line-height:2'),CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->create_time),"long","short"));
    }

    //Ретурним ссылку для item-ов
    public function getMenuLink()
    {
        return CHtml::link($this->item_name,Yii::app()->createUrl('menu/backend/menuitems'),array('update'=>'#manage_menu'),array('title'=>$this->item_name,'data-toggle'=>'tooltip',"style"=>"text-align:center"));
    }

    //
    public function getPublishedItem()
    {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status=1';
        return $this->menuItem[0]->count($criteria);
    }

    //
    public function getUnpublishedItem()
    {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status=0';
        return $this->menuItem[0]->count($criteria);
    }

    /**
     * Генерация li элементов для бокового сайдбара админки
     * @param $module
     * @return array
     */
    protected function getItems($module)
    {
        Yii::app()->getModule($module)->basePath = Yii::getPathOfAlias('application.modules.'.$module);
        $label = ucfirst($module);
        $module = strtolower($module);
        $item = array(
            array('faicon'=>'cogs','label'=>Yii::t($label.'Module.base','Manage '.$module),'url'=>Yii::app()->createUrl($module.'/backend/admin'),'active'=>Yii::app()->request->url == Yii::app()->createUrl($module.'/backend/admin')),
            array('faicon'=>'plus-square','label'=>Yii::t($label.'Module.base','Create '.$module),'url'=>Yii::app()->createUrl($module.'/backend/create'),'active'=>Yii::app()->request->url == Yii::app()->createUrl($module.'/backend/create')),
            array('faicon'=>'list','label'=>Yii::t($label.'Module.base','All '.$module),'url'=>Yii::app()->createUrl($module.'/backend/index'),'active'=>Yii::app()->request->url == Yii::app()->createUrl($module.'/backend/index'),'visible'=>$module !== 'menu' && $module != 'user' && $module != 'category' ),
            array('faicon'=>'trash-o','label'=>Yii::t($label.'Module.base','Delete '.$module),'url'=>Yii::app()->createUrl($module.'/backend/delete',array('id'=>Yii::app()->request->getParam('id'))),'visible'=>Yii::app()->controller->action->id == 'view'),
            array('faicon'=>'refresh','label'=>Yii::t($label.'Module.base','Update '.$module),'url'=>Yii::app()->createUrl($module.'/backend/update',array('id'=>Yii::app()->request->getParam('id'))),'visible'=>Yii::app()->controller->action->id == 'view'),

        );
        return $item;
    }

    /**
     * Генерация ul элементов для бокового сайдбара админки
     * @return array
     */
    public  function getMenuItems()
    {
        $item = array();
        $modules = Yii::app()->getModules();
        if(count($modules))
        {
            foreach($modules as $module=>$options)
            {
                if($module != 'gii')
                {
                    Yii::app()->getModule($module)->basePath = Yii::getPathOfAlias('application.modules.'.$module);
                    $item[$module] = array('faicon'=>$this->getIcon($module),'label'=>Yii::t(ucfirst($module).'Module.base',ucfirst($module)),'facaret'=>'angle-left','selected'=>'selected','url'=>'#'.$module,'linkOptions'=>array('data-toggle'=>'collapse','data-parent'=>'#accordion'),'itemOptions'=>array('class'=>'panel '),'active'=>$this->checkActivity($module),'items'=>$this->getItems($module),
                        'submenuOptions'=>array('id'=>$module,'class'=>'panel-collapse collapse sub-menu'),
                        'htmlOptions'=>array('style'=>'float:left')
                    );
                }
            }
            return $item;
        }
    }
    /**
     * Генерация Иконок для бокового сайдбара админки
     * @param $module
     * @return string
     */
    protected function getIcon($module)
    {
        switch($module)
        {
            case "article":
                return 'list-alt';break;
            case "category":
                return 'folder';break;

            case "menu":
                return 'list-ul';break;

            case "user":
                return 'user';break;
            default:
                return '';
        }
    }
    /**
     *
     * @param $module
     * @return bool
     */
    protected function checkActivity($module)
    {
        if(Yii::app()->controller->module->getId() === $module)
        {
            return true;
        }
        return false;
    }
}
